
import * as API_Shop from '../../../api/shop.js'
import * as API_Promotions from '../../../api/promotions.js'
import * as API_Goods from '../../../api/goods.js'
import * as API_Members from '../../../api/members.js'
import * as API_Trade from '../../../api/trade.js'
import {
  Foundation
} from '../../../ui-utils/index.js'
var WxParse = require('../../../lib/wxParse/wxParse.js');
let util = require('../../../utils/util.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgUrls:[],
    indicatorDots:true,
    indicatorColor:"rgba(0, 0, 0, .3)",
    autoplay:true,
    circular:true,
    tabIndex: 0, //tab切换
    shop_id: 0,
    shop: [],
    is_collection: false, //店铺是否收藏
    collection_num: 0, //店铺收藏数
    shopsildes: [], //店铺幻灯片
    coupons: '', //优惠券列表
    newGoods: [], // 新品上架
    hotGoods: [], // 热销商品
    recGoods: [], // 推荐商品
    scrollHeight: 0,
    scrollTop: 0,
    showGoTop: false, //返回顶部按钮
    promotionList: [],
    page_no: 1,
    page_size: 10,
    finished: false,
    newList: [],
    tagGoods: [],
    categories: [],
    current: [],
    homeFloor: [],
    total_price: '0.00',
    in_store: true, // 配送地区是否有货状态 默认有货,
    buyNum: 1,//数量,
    keyword:'',//搜索的关键词
    
  },
  //tab切换
  tabs(e) {
    let index = parseInt(e.currentTarget.dataset.index)
    if (index == 1) {
      this.GET_HomeData()
    }
    if (index == 1) {
      this.GET_PromotionData()
    }
    if (index == 2) {
      this.GET_NewGoods()
    }
    if (index == 3) {
      this.GET_Active()
    }
    if (index == 4) {
      this.GET_Category()
    }
    this.setData({
      tabIndex: index
    })
  },
  //获取店铺基本信息
  getShopInfo() {
    let that = this;
    API_Shop.getShopBaseInfo(this.data.shop_id).then(response => {
      console.log('response',response);
      
      that.setData({
        shop: response,
        collection_num: response.shop_collect
      })
      wx.setNavigationBarTitle({
        title: response.shop_name
      })
      // WxParse.wxParse('shopDetail', 'html', response.shop_desc, that)
    })
    this.GET_HomeData()
    // this.lunbo()
    that.getShopSildes()
    // that.getShopCoupons()
    // that.getShopTagGoods()
    that.getShopIsCollect()
  },
  //获取首页数据
  GET_HomeData() {
    let floorList = [];
    API_Shop.getAppHomeData({
      shop_id: this.data.shop_id,
      type: "wap_2"
    }).then(res => {
      if (res) {
        let model_data = JSON.parse(res.model_data);
        let static_data = JSON.parse(res.static_data);
        let goods_volist = res.goods_volist;
        let i = 0;
        let g_i = 0;
        console.log(model_data)
        console.log(static_data[0])
        model_data.map((item, index) => {
          if (item.type === "IMAGE") {
            let blockList = JSON.parse(static_data[i++]);
            floorList.push({
              blockList: blockList,
              tpl_id: item.tpl_id,
              type: item.type
            });
          } else {
            let blockValue = goods_volist.slice(g_i, g_i + item.number);
            g_i = g_i + item.number;
            let blockList = [];
            blockValue.map(b => {
              blockList.push({
                block_value: b,
                block_type: "GOODS",
                block_opt: ""
              });
            });
            floorList.push({
              blockList: blockList,
              tpl_id: item.tpl_id,
              type: item.type
            });
          }
        });
      }
      console.log(floorList)
      floorList.map(item => {
        if (item.type == 'GOODS') {
          item.blockList.map(goods => {
            goods.block_value.price = Foundation.formatPrice(goods.block_value.price)
          })
        }
      })
      this.setData({
        homeFloor: floorList
      })
    });
  },
  //获取促销商品
  GET_PromotionData() {
    API_Shop.getAppHomeData({
      shop_id: this.data.shop.shop_id,
      // shop_id: 15,
      type: "PROMOTION"
    }).then(response => {
      response.goods_volist.map(item => {
        item.price = Foundation.formatPrice(item.price)
      })
      this.setData({
        promotionList: response.goods_volist
      })
    });
  },
  //获取上新商品
  GET_NewGoods() {
    API_Shop.newGoods({
      page_no: 1,
      page_size: 50,
      shop_id: this.data.shop_id
      // shop_id: 15
    })
      .then(response => {
        response.data.map(item => {
          // await API_Goods.getGoods(item.goods_id)
          item.price = Foundation.formatPrice(item.price)
        })
        this.setData({
          newList: response.data
        })
      })
  },
  async GET_Active() {
    let data = await API_Shop.getShopTag({
      seller_id: this.data.shop_id,
      page_no: 1,
      page_size: 99999
    })
    let tagGoods = []
    let promise = []
    data.data.map(item => {
      promise.push(API_Shop.getTagGoods(this.data.shop_id, item.mark, 6))
    })
    let value = await Promise.all(promise)
    data.data.map((item, index) => {
      value[index].map(goods => {
        goods.price = Foundation.formatPrice(goods.price)
      })
      tagGoods.push({
        title: item.tag_name,
        data: value[index],
        mark: item.mark
      })
    })
    this.setData({
      tagGoods
    })
  },

  GET_Category() {
    API_Shop.getShopCategorys(this.data.shop_id)
      .then(res => {
        this.setData({
          categories: res,
          current: res[0] || []
        })
      })
  },
  switchCate(event) {
    var that = this;
    var {
      id
    } = event.currentTarget.dataset;
    if (this.data.current.shop_cat_id == id) {
      return false;
    }
    for (var item of that.data.categories) {
      if (item.shop_cat_id == id) {
        that.setData({
          current: item
        });
        break;
      }
    }
  },
  //搜索
  inputChange: function (e) {
    this.setData({keyword: e.detail.value || ''});
    wx.navigateTo({
      url: "/pages/shop/goods_list/goods_list?shop_id=" + this.data.shop_id,
    })
    // this.getSearchKeyword()
  },
  //企业详情
  onShopInfo() {
    wx.navigateTo({
      url: '/pages/shop/shop_info/shop_info?shop_id=' + this.data.shop_id
    })
  },
  //扫码
  onPay() {
    wx.navigateTo({
      url: '/pages/shop/shop_pay/shop_pay?shop_id=' + this.data.shop_id
    })
  },
  //获取店铺幻灯片
  getShopSildes() {
    API_Shop.getShopSildes(this.data.shop_id).then(response => {
      this.setData({
        shopsildes: response
      })
    })
    console.log(this.data.shopsildes)
    console.log(this.data)
    console.log(shopsildes)
  },
  onPageScroll(e) {
    if (e.scrollTop >= 155) {
      this.isScroll = true;
      // this.inAnimationStart();
    }
    if (e.scrollTop < 155) {
      this.isScroll = false;
      // this.outAnimationStart();
    }
  },
  //获取店铺优惠券
  getShopCoupons() {
    API_Promotions.getShopCoupons(this.data.shop_id).then(response => {
      this.setData({
        coupons: response
      })
    })
  },
  //领取店铺优惠券
  handleReceiveCoupon(e) {
    const coupon = e.currentTarget.dataset.coupon
    if (!wx.getStorageSync('refresh_token')) {
      wx.showToast({
        title: '您还未登录!',
        image: '/static/images/icon_error.png'
      })
      return false
    }
    API_Members.receiveCoupons(coupon.coupon_id).then(() => {
      wx.showToast({
        title: '领取成功'
      })
    })
  },
  //获取店铺标签商品
  getShopTagGoods() {
    API_Goods.getTagGoods(this.data.shop_id, 'hot', 10).then(response => {
      response.forEach(key => {
        key.price = Foundation.formatPrice(key.price)
      })
      this.setData({
        hotGoods: response
      })
    })
    API_Goods.getTagGoods(this.data.shop_id, 'new', 10).then(response => {
      response.forEach(key => {
        key.price = Foundation.formatPrice(key.price)
      })
      this.setData({
        newGoods: response
      })
    })
    API_Goods.getTagGoods(this.data.shop_id, 'recommend', 10).then(response => {
      response.forEach(key => {
        key.price = Foundation.formatPrice(key.price)
      })
      this.setData({
        recGoods: response
      })
    })
  },
  //获取店铺是否收藏
  getShopIsCollect() {
    if (wx.getStorageSync('refresh_token')) {
      API_Members.getShopIsCollect(this.data.shop_id).then(response => {
        this.setData({
          is_collection: response.message
        })
      })
    }
  },
  //收藏店铺
  collectionShop() {
    if (!wx.getStorageSync('refresh_token')) {
      wx.showToast({
        title: '您还未登录!',
        image: '/static/images/icon_error.png'
      })
      return false
    }
    if (this.data.is_collection) {
      API_Members.deleteShopCollection(this.data.shop_id).then(() => {
        this.setData({
          is_collection: false,
          collection_num: this.data.collection_num -= 1
        })
        wx.showToast({
          title: '取消收藏成功!'
        })
      })
    } else {
      API_Members.collectionShop(this.data.shop_id).then(() => {
        this.setData({
          is_collection: true,
          collection_num: this.data.collection_num += 1
        })
        wx.showToast({
          title: '收藏成功!'
        })
      })
    }
  },
  //滚动到指定位置显示返回顶部按钮
  scroll: function (e) {
    let that = this
    if (e.detail.scrollTop > 200) {
      that.setData({
        showGoTop: true
      })
    } else {
      that.setData({
        showGoTop: false
      })
    }
  },
  //返回顶部
  goTop() {
    this.setData({
      scrollTop: 0
    })
  },
  //模板三中点击导航跳转到指定位置
  hotanchor() {
    this.setData({
      scrollTop: 400
    })
  },
  recanchor() {
    this.setData({
      scrollTop: 3028
    })
  },
  newanchor() {
    this.setData({
      scrollTop: 6142
    })
  },
  /* 购物车 */
  GET_car() {
    API_Trade.getCarts("all", 'CART').then(response => {
      //console.log(this.shopGoods, 1);
      let num = 0;
      response.cart_list.forEach(item => {
        if (item.seller_id == this.data.shop_id) {
          item.sku_list.forEach(it => {
            num += it.num;
          })
        }
      })
      this.setData({ total_price: Foundation.formatPrice(response.total_price.total_price), checkedCount: num })
    });
  },
  /** 加入购物车 */
  handleAddToCart(e) {
    //console.log(e, 1477777)
    if (!wx.getStorageSync('refresh_token')) {
      wx.showToast({
        title: '您还未登录!',
        image: '/static/images/icon_error.png'
      })
      return false
    }
    const {
      buyNum
    } = this.data
    let id = e.currentTarget.dataset.id;
    API_Goods.getGoodsSkus(id).then(data => {
      // console.log(response);
      let sku_id = data[0].sku_id;
      // console.log(sku_id);
      API_Trade.addToCart(sku_id, buyNum, '').then(response => {
        this.GET_car();
        //更新购物车数量
        wx.showModal({
          title: '提示',
          content: '加入购物车成功，要去看看么？',
          confirmColor: '#f42424',
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/cart/cart'
              })
            }
          }
        })
      });
    });
  },
  /* 申请会员 */
  applyMember() {
    if (!wx.getStorageSync('refresh_token')) {
      wx.showToast({
        title: '您还未登录!',
        image: '/static/images/icon_error.png'
      })
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/auth/login/login'
        })
      }, 800)

    } else {
      wx.navigateTo({
        url: '/pages/shop/apply_member/apply_member?shop_id=' + this.data.shop_id
      })
    }
  },
  /* 立即下单 */
  goOrder() {
    if (!wx.getStorageSync('refresh_token')) {
      wx.showToast({
        title: '您还未登录!',
        image: '/static/images/icon_error.png'
      })
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/auth/login/login'
        })
      }, 800)
    } else {
      this.handleCheckout();
    }
  },
  /** 去结算 */
  handleCheckout: util.throttle(function () {
    if (!this.data.checkedCount) {
      wx.showToast({ title: '您还没有选中商品哦', icon: 'none' })
      return false
    }
    wx.navigateTo({
      url: '/pages/shopping/checkout/checkout?way=CART'
    })
  }),
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let that = this
    that.setData({
      shop_id: parseInt(options.id)
    })
    wx.getSystemInfo({
      success: function (res) {
        // console.log(res)
        // console.log(res.windowHeight * 750 / res.windowWidth)
        that.setData({
          scrollHeight: (res.windowHeight * 750 / res.windowWidth - 344) + 'rpx'
        })
      },
    })
    that.getShopInfo();
    // that.getShopSildes();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    API_Trade.checkAll(0).then(() => {
      API_Trade.checkShop(this.data.shop_id, 1).then(() => {
        console.log('购物车中只选中当前店铺的商品');
        this.GET_car();
      })
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.tabIndex == 2 && !this.data.finished) {
      this.setData({
        page_no: this.data.page_no + 1
      })
      this.GET_NewGoods()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})